package qeb.handheldmedical.patient;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import qeb.handheldmedical.R;
import qeb.handheldmedical.adapter.PatientAdapter;
import qeb.handheldmedical.adapter.PatientGroupAdapter;
import qeb.handheldmedical.adapter.SlideListView;
import qeb.handheldmedical.dialog.MultiDialog;
import qeb.handheldmedical.helper.MaterApp;
import qeb.handheldmedical.helper.WSHelper;
import qeb.handheldmedical.instruction.CheckInstruction;
import qeb.handheldmedical.model.InPatient;
import qeb.handheldmedical.model.Medicine;
import qeb.handheldmedical.model.User;

public class InPatientList extends Activity {
    private ExpandableListView lvPatient;
    private PatientGroupAdapter groupadapter;
    private SlideListView slideListView;
    private PatientAdapter adapter;
    private TextView tv_title, tv_title1, tv_titleName;
    private List<String> list = new ArrayList<String>();
    // private LinearLayout ll_search_bar;
    private User usr = new User();
    private JSONArray patientJsonArray;
    private JSONObject jobj;
    private InPatient ip;
    private MaterApp meterApp;
    private String patientState;

    private String keyword;

    // private Include search_bar;

    private Button btn_title_back, btn_title_right, btn_search, btn_sx;

    private EditText edt_keyword;
    private Spinner mSpinner;
    private ArrayAdapter<String> myAdapter = null;
    // private boolean isRunning=false;
    private MultiDialog mDialog;

    private static final int UPDATE = 0;
    private TextView merge ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.inpatient_list);
        meterApp = MaterApp.getInstance();
        init();
        initBarReciever();
    }

    public static final String BAR_READ_ACTION = "SYSTEM_BAR_READ";// 条码广播
    public static final String RFID_READ_ACTION = "SYSTEM_RFID_READ";// RFID广播
    public static final String NLSCAN_SCANNER = "nlscan.action.SCANNER_RESULT";// 新大陆机型
    public String action;// 扫描
    private BroadcastReceiver InPatientListReciever;
    // honeywell
    private final static String TAG = "ScanResultReceiver";
    private static final String INTENT_ACTION_SCAN_RESULT = "com.honeywell.tools.action.scan_result";
    private static final String SCANACTION = "com.android.server.scannerservice.broadcastxhyy";// 小码哥
    private static final String Neusoft = "com.neusoft.action.scanner.read";// 东软
    private Medicine medicine ;

    public  boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }
    private void initBarReciever() {

        InPatientListReciever = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                // TODO Auto-generated method stub
                action = intent.getAction();
                Log.d("scan", "InPatientList");
                String BAR_value = "";
                String STATE_value = "ok";

                    if (action.equals(BAR_READ_ACTION)) {
                    BAR_value = intent.getStringExtra("BAR_VALUE").trim();
                } else if (action.equals(RFID_READ_ACTION)) {
                    BAR_value = intent.getStringExtra("RFID_VALUE").trim();
                } else if (action.equals(INTENT_ACTION_SCAN_RESULT)) {
                    if (intent.hasExtra("decode_rslt")) {
                        BAR_value = intent.getStringExtra("decode_rslt");
                    }
                } else if (action.equals(SCANACTION)) {
                    BAR_value = intent.getStringExtra("scannerdata").replaceAll("\r|\n", "");
                } else if (action.equals(Neusoft)) {
                    BAR_value = intent.getStringExtra("scanner_value").replaceAll("\r|\n", "");
                } else if (action.equals(NLSCAN_SCANNER)) {
                    STATE_value = intent.getStringExtra("SCAN_STATE");
                    BAR_value = TextUtils.isEmpty(intent.getStringExtra("SCAN_BARCODE1")) ? intent.getStringExtra("SCAN_BARCODE2") : intent.getStringExtra("SCAN_BARCODE1");
                    BAR_value = BAR_value.replaceAll("\r|\n", "");
                }
                if (!BAR_value.equals("ERROR") || STATE_value.equals("ok")) {// 扫描出错
                    ip = new InPatient();
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("hiszyxh", BAR_value);
                    try {
                        JSONArray pInfoArray = WSHelper.getWebserviceFun("GetPatientInfoByHiszyxh", map);
                        if (pInfoArray != null) {
                            ip.getValue(pInfoArray.getJSONObject(0));
                        }

                        if (!TextUtils.isEmpty(ip.BAH)) {
                            Intent newintent = new Intent(getApplicationContext(), CheckInstruction.class);
                            newintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            newintent.putExtra("patientinfo", ip);
                            newintent.putExtra("userinfo", usr);
                            newintent.putExtra("ly", "2");
                            startActivity(newintent);
                        } else {
                            Toast tt = Toast.makeText(InPatientList.this, "病人不存在！", Toast.LENGTH_LONG);
                            tt.show();
                            tt.setGravity(Gravity.CENTER, 0, 0);
                        }
                    } catch (Exception e) {
                        Toast tt = Toast.makeText(InPatientList.this, "获取病人信息失败！", Toast.LENGTH_LONG);
                        tt.show();
                    }
                } else {
                    Toast tt = Toast.makeText(InPatientList.this, "扫描出错！", Toast.LENGTH_LONG);
                    tt.show();
                    tt.setGravity(Gravity.CENTER, 0, 0);
                }
            }

        };
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // handler.removeCallbacks(myRunnable);
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub

        InPatientList.this.unregisterReceiver(InPatientListReciever);

        super.onPause();
    }

    @Override
    protected void onRestart() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BAR_READ_ACTION);
        filter.addAction(RFID_READ_ACTION);
        filter.addAction(INTENT_ACTION_SCAN_RESULT);
        filter.addAction(SCANACTION);
        filter.addAction(Neusoft);
        filter.addAction(NLSCAN_SCANNER);
        registerReceiver(InPatientListReciever, filter);
        super.onRestart();
    }

    @Override
    protected void onResume() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BAR_READ_ACTION);
        filter.addAction(RFID_READ_ACTION);
        filter.addAction(INTENT_ACTION_SCAN_RESULT);
        filter.addAction(SCANACTION);
        filter.addAction(Neusoft);
        filter.addAction(NLSCAN_SCANNER);
        registerReceiver(InPatientListReciever, filter);
        super.onResume();
    }

    private void init() {
        try {
            usr = (User) getIntent().getSerializableExtra("userinfo");
            patientState = getIntent().getSerializableExtra("patientstate")
                    .toString();
        } catch (Exception e) {
            // TODO Auto-generated catch block
        }
        merge = findViewById(R.id.merge);
        merge.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(InPatientList.this,MedicineListActivity.class);
                intent.putExtra("userinfo",usr);
                startActivity(intent);
            }
        });
        lvPatient = (ExpandableListView) findViewById(R.id.lvPatient);
        tv_title = (TextView) findViewById(R.id.tv_top_title);
        btn_title_back = (Button) findViewById(R.id.btn_title_back);
        btn_title_back.setOnClickListener(MyOnClickListener);
        tv_titleName = (TextView) findViewById(R.id.tv_title);
        tv_titleName.setText("病人列表");
        tv_title1 = (TextView) findViewById(R.id.tv_title1);
        tv_title1.setText(usr.DNAME);
        btn_title_right = (Button) findViewById(R.id.btn_title_right);
        btn_title_right.setOnClickListener(MyOnClickListener);
        btn_sx = (Button) findViewById(R.id.btn_sx);
        btn_sx.setOnClickListener(MyOnClickListener);
        if (patientState != null) {
            if (patientState.equals("1")) {
                patientState = "1";
                tv_title.setText("在院病人");
            } else {
                tv_title.setText("出院病人");
            }

            // dataBind();
        } else {
            tv_title.setText("病人查询");
            // btn_title_right.setClickable(false);
            btn_title_right.setText("刷新");
        }

        mDialog = new MultiDialog(InPatientList.this,
                MultiDialog.DialogType.WAITING);
        mDialog.setMessage("正在加载，请稍候......");
        mDialog.show();
        new Thread() {

            @Override
            public void run() {
                try {
                    getData();
                    myHandler.sendEmptyMessage(UPDATE);
                } catch (Exception e) {
                    // TODO: handle exception
                    // Log.v("LineExam", e.toString());
                }
            }
        }.start();
    }

    private void getData() {
        if (usr.BQID != null) {
            // keyword = edt_keyword.getText().toString();
            // patientJsonArray=new JSONArray();
            // slideListView.removeAllViews();
            // patientJsonArray =
            // WSHelper.GetPatientList(usr.BQID,patientState,keyword,"");
            Map<String, String> map = new HashMap<String, String>();
            map.put("deptID", usr.BQID);
            map.put("userID", usr.DID);

            patientJsonArray = WSHelper.getWebserviceFun("GetPatientList4PDA",
                    map);
        }
    }

    /* 系统主菜单点击事件（在院病人、门诊病人等） */
    private OnClickListener MyOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO 自动生成的方法存根
            // Bundle bundle=new Bundle();
            switch (v.getId()) {
                case R.id.btn_title_back:// 返回按钮
                    InPatientList.this.finish();
                    break;
                case R.id.btn_sx:
                case R.id.btn_title_right:// 刷新按钮

                    // edt_keyword.setText("");
                    mDialog = new MultiDialog(InPatientList.this,
                            MultiDialog.DialogType.WAITING);
                    mDialog.setMessage("正在加载，请稍候......");
                    mDialog.show();
                    new Thread() {

                        @Override
                        public void run() {
                            try {
                                getData();
                                myHandler.sendEmptyMessage(UPDATE);
                            } catch (Exception e) {
                                // TODO: handle exception
                                Log.v("Login", e.toString());
                            }
                        }
                    }.start();

                    break;
                case R.id.btn_search:// 搜索按钮
                    mDialog = new MultiDialog(InPatientList.this,
                            MultiDialog.DialogType.WAITING);
                    mDialog.setMessage("正在加载，请稍候......");
                    mDialog.show();
                    new Thread() {

                        @Override
                        public void run() {
                            try {
                                getData();
                                myHandler.sendEmptyMessage(UPDATE);
                            } catch (Exception e) {
                                // TODO: handle exception
                                Log.v("Login", e.toString());
                            }
                        }
                    }.start();
                    break;
                default:
                    break;
            }
        }
    };

    Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE:
                    dataBindGroup();
                    // btn_search.setClickable(true);
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
            // isRunning=false;
            mDialog.cancel();
        }
    };

    private void dataBindGroup() {
        if (patientJsonArray != null && patientJsonArray.length() > 0) {
            groupadapter = new PatientGroupAdapter(this, patientJsonArray);
            lvPatient.setAdapter(groupadapter);
            for (int i = 0; i < lvPatient.getCount(); i++) {
                try {
                    JSONObject work = patientJsonArray.getJSONObject(i);
                    if (work.getString("ISOPEN").equals("1")) {
                        lvPatient.expandGroup(i);
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            lvPatient.setOnChildClickListener(new ChildClickListener());
        }
    }

    /**
     * 绑定ItemList点击事件
     *
     * @author Administrator
     */
    class ChildClickListener implements OnChildClickListener {

        @Override
        public boolean onChildClick(ExpandableListView lv, View v,
                                    int groupPosition, int childPosition, long id) {
            // TODO Auto-generated method stub
            ip = new InPatient();
            try {
                JSONObject work = patientJsonArray.getJSONObject(groupPosition);
                String strPatient = work.getString("PATIENTS");
                JSONArray patients = new JSONArray(strPatient);
                jobj = patients.getJSONObject(childPosition);

                String strZyxh = jobj.getString("BAH");
                Map<String, String> map = new HashMap<String, String>();
                map.put("hiszyxh", strZyxh);

                JSONArray pInfoArray = WSHelper.getWebserviceFun("GetPatientInfoByHiszyxh", map);
                if (pInfoArray != null) {
                    ip.getValue(pInfoArray.getJSONObject(0));
                }

                if (!TextUtils.isEmpty(ip.ZYXH)) {
                    Intent intent = new Intent(getApplicationContext(), PatientMain.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.putExtra("patientInfo", ip);
                    intent.putExtra("userinfo", usr);
                    startActivity(intent);
                } else {
                    Toast tt = Toast.makeText(InPatientList.this, "获取病人信息失败，请重试！", Toast.LENGTH_LONG);
                    tt.show();
                }
            } catch (Exception e) {
                Toast tt = Toast.makeText(InPatientList.this, "获取病人信息失败！", Toast.LENGTH_LONG);
                tt.show();
            }
            return true;
        }
    }

    public class ItemSelectedListenerImpl implements OnItemSelectedListener {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view,
                                   int position, long id) {
            // TODO 自动生成的方法存根
            // InPatientList.this.myAdapter=new
            // ArrayAdapter<String>(this,android.R.layout.simple_gallery_item,parent.getItemAtPosition(position));
            /*
             * Toast tt = Toast.makeText(InPatientList.this, "选择："+
             * position,Toast.LENGTH_LONG); tt.show();
             */
            if (usr.BQID != null) {
                // keyword = edt_keyword.getText().toString();
                patientJsonArray = WSHelper.GetPatientList(usr.BQID,
                        patientState, keyword, String.valueOf(position));
                // dataBind();
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // TODO 自动生成的方法存根

        }
    }

    /*
     * (non-Javadoc)
     *
     * @see android.app.Activity#onStop()
     */
    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
    }

}
